package com.mmall.service.impl;

import com.mmall.common.Const;
import com.mmall.common.ServiceResponse;
import com.mmall.common.TokenCache;
import com.mmall.dao.UserMapper;
import com.mmall.pojo.User;
import com.mmall.service.IUserService;
import com.mmall.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service("iUserService")
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public ServiceResponse<User> login(String username, String password) {
        int resultCount = userMapper.checkUsername(username);
        if (resultCount == 0) {
            return ServiceResponse.createByErrorMessage("用户名不存在");

        }
        //密码登录md5
        String md5pass = MD5Util.MD5EncodeUtf8(password);
        User user = userMapper.selectLogin(username, md5pass);
        if (user == null) {
            return ServiceResponse.createByErrorMessage("密码错误");
        }
        user.setPassword(StringUtils.EMPTY);
        return ServiceResponse.createBySuccess("登录成功", user);

    }

    @Override
    public ServiceResponse<String> register(User user) {
        ServiceResponse validResp = this.checkvalid(user.getUsername(), Const.USERNAME);
        if (!validResp.inSuccess()) {
            return validResp;
        }
        validResp = this.checkvalid(user.getEmail(), Const.EMAIL);
        if (!validResp.inSuccess()) {
            return validResp;
        }
        user.setRole(Const.Role.ROLE_CUSTOMER);
        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));
        int resultcount = userMapper.insert(user);
        if (resultcount == 0) {
            return ServiceResponse.createByErrorMessage("注册失败");
        }
        return ServiceResponse.createBySuccessMessage("注册成功");
    }

    @Override
    public ServiceResponse<String> checkvalid(String str, String type) {
        if (StringUtils.isNotBlank(type)) {
            if (Const.USERNAME.equals(type)) {
                int resultcount = userMapper.checkUsername(str);
                if (resultcount > 0) {
                    return ServiceResponse.createByErrorMessage("用户名存在");
                }
            }
            if (Const.EMAIL.equals(type)) {

                int resultcount = userMapper.checkEmail(str);
                if (resultcount > 0) {
                    return ServiceResponse.createByErrorMessage("邮箱已存在");

                }
            }
        } else {
            return ServiceResponse.createByErrorMessage("参数错误");
        }
        return ServiceResponse.createBySuccessMessage("校验成功");
    }

    @Override
    public ServiceResponse<String> selectQuestion(String username) {
        ServiceResponse validResp = this.checkvalid(username, Const.USERNAME);
        if (validResp.inSuccess()) {
            return ServiceResponse.createByErrorMessage("用户不存在");
        }
        String question = userMapper.selectQuestionByUsername(username);
        if (StringUtils.isNotBlank(question)) {
            return ServiceResponse.createBySuccess(question);
        }

        return ServiceResponse.createByErrorMessage("找回密码问题为空");
    }

    public ServiceResponse<String> checkAnswer(String username, String question, String answer) {
        int resultCount = userMapper.checkAnswer(username, question, answer);
        if (resultCount > 0) {
            String token = UUID.randomUUID().toString();
            TokenCache.setKey(TokenCache.TokenPrefix + username, token);
            return ServiceResponse.createBySuccess(token);
        }
        return ServiceResponse.createByErrorMessage("答案错误");
    }

    public ServiceResponse<String> forgetResetPassowrd(String username, String passwordnew, String token) {
        if (StringUtils.isBlank(token)) {
            return ServiceResponse.createByErrorMessage("参数错误，无token");
        }
        ServiceResponse validResp = this.checkvalid(username, Const.USERNAME);
        if (validResp.inSuccess()) {
            return ServiceResponse.createByErrorMessage("用户名不存在");
        }
        String t = TokenCache.getkey(TokenCache.TokenPrefix + username);
        if (StringUtils.isBlank(t)) {
            return ServiceResponse.createByErrorMessage("token无效或者过期");
        }
        if (StringUtils.equals(t, token)) {
            String md5pwd = MD5Util.MD5EncodeUtf8(passwordnew);
            int rawCount = userMapper.updatePasswordByUsername(username, md5pwd);
            if (rawCount > 0) {
                return ServiceResponse.createBySuccessMessage("修改密码成功");
            } else {
                return ServiceResponse.createByErrorMessage("toekn错误，请重新获取");
            }
        }
        return ServiceResponse.createByErrorMessage("修改失败");
    }

    public ServiceResponse<String> resetPassword(String passwordold, String passwordnew, User user) {
        int result = userMapper.checkPassword(MD5Util.MD5EncodeUtf8(passwordold), user.getId());
        if (result == 0) {
            return ServiceResponse.createByErrorMessage("旧密码错误");
        }
        user.setPassword(MD5Util.MD5EncodeUtf8(passwordnew));
        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if (updateCount > 0) {
            return ServiceResponse.createBySuccessMessage("密码更新成功");
        }
        return ServiceResponse.createByErrorMessage("密码更新失败");
    }

    public ServiceResponse<User> updateinfomation(User user) {
        //username 不能更新 email 校验
        int resultCount = userMapper.checkemailByid(user.getEmail(), user.getId());
        if (resultCount > 0) {
            return ServiceResponse.createByErrorMessage("email已存在");
        }
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setEmail(user.getEmail());
        updateUser.setPhone(user.getPhone());
        updateUser.setQuestion(user.getQuestion());
        updateUser.setAnswer(user.getAnswer());

        int updatCount = userMapper.updateByPrimaryKeySelective(updateUser);
        if (updatCount > 0) {
            return ServiceResponse.createBySuccess("更新信息成功", updateUser);
        }
        return ServiceResponse.createByErrorMessage("更新信息失败");
    }

    public ServiceResponse<User> getinformation(Integer userID) {
        User user = userMapper.selectByPrimaryKey(userID);
        if (user == null) {
            return ServiceResponse.createByErrorMessage("找不到用户");
        }
        user.setPassword(StringUtils.EMPTY);
        return ServiceResponse.createBySuccess(user);

    }

    //category
    public ServiceResponse checkAdminRole(User user) {
        if (user != null && user.getRole().intValue() == Const.Role.ROLE_ADMIN) {
            return ServiceResponse.createBySuccess();
        }
        return ServiceResponse.createByError();
    }

}
